<?php

namespace App\Libraries\DingTalk;

class DingTalkUser extends DingTalkBase
{
    public function getOptions(array $json = []): array
    {
        $options = [];
        $options['headers'] = ['Content-Type' => 'application/json; charset=UTF-8'];

        if (! empty($json)) {
            $options['json'] = $json;
        }

        return $options;
    }

    /**
     * 根据手机号获取用户ID
     *
     * @param  string $mobile 手机号
     * @return array
     */
    public function getUserByMobile(string $mobile = ''): array
    {
        $options = $this->getOptions([
            'mobile' => $mobile,
            'support_exclusive_account_search' => true,
        ]);

        return $this->requestByPost(
            'https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token=' . $this->getAccessToken(),
            $options
        );
    }

    /**
     * 根据用户ID获取用户详情
     *
     * @param  string $userId 钉钉用户ID
     * @return array
     */
    public function getUser(string $userId = ''): array
    {
        $options = $this->getOptions([
            'userid' => $userId,
        ]);

        return $this->requestByPost(
            'https://oapi.dingtalk.com/topapi/v2/user/get?access_token=' . $this->getAccessToken(),
            $options
        );
    }

    /**
     * 获取用户ID列表
     *
     * @param  int|int $dept_id 部门ID 1: 根部门
     * @param  int     $deptId
     * @return array
     */
    public function getUserIdList(int $deptId = 1): array
    {
        $options = $this->getOptions([
            'dept_id' => $deptId,
        ]);

        return $this->requestByPost(
            'https://oapi.dingtalk.com/topapi/user/listid?access_token=' . $this->getAccessToken(),
            $options
        );
    }

    /**
     * 获取部门用户列表
     *
     * @param  int|int $deptId 部门ID
     * @param  int|int $cursor 页码
     * @param  int|int $size   每页数量
     * @return array
     */
    public function getDeptUserList(int $deptId = 1, int $cursor = 1, int $size = 100): array
    {
        $options = $this->getOptions([
            'dept_id' => $deptId,
            'cursor' => $cursor,
            'size' => $size,
        ]);

        return $this->requestByPost(
            'https://oapi.dingtalk.com/topapi/user/listsimple?access_token=' . $this->getAccessToken(),
            $options
        );
    }
}
